package com.atjava.webspider.database.support;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.atjava.webspider.database.JDBCManager;

public class MySQLManager extends JDBCManager{
	
	public static final String [] TYPE_TABLE = {"TABLE"};
	
	public MySQLManager(Connection con) {
		super(con);
	}
	
	public List<String> getTables() throws Exception{
		ResultSet rs = null;
		Statement st = connection.createStatement();
		List<String> tables = new ArrayList<String>();
		try {
			DatabaseMetaData meta = connection.getMetaData();
			rs = meta.getTables(null, null, null, TYPE_TABLE);
			while(rs.next()){
				String name = rs.getString(3);
				tables.add(name);
			}
		} catch (Exception e) {
			throw e;
		} finally{
			closeResultSet(rs);
			closeStatement(st);
		}
		return tables;
	}
	
	public List<String> getTableFields(String table) throws Exception{
		ResultSet rs = null;
		Statement st = connection.createStatement();
		List<String> fields = new ArrayList<String>();
		try {
			rs = st.executeQuery("select * from " + table);
			int n = rs.getMetaData().getColumnCount();
			for(int i=1;i<=n;i++){
				fields.add(rs.getMetaData().getColumnName(i));
			}
		} catch (Exception e) {
			throw e;
		} finally{
			closeResultSet(rs);
			closeStatement(st);
		}
		return fields;
	}
	
	/**
	 * only number primary key
	 * @param table
	 * @return
	 * @throws Exception
	 
	public int getPrimayKeyVal(String table)throws Exception{
		String pkey = getPrimaryKey(table);
		List<Object []> result = query("select max("+pkey+") from " + table);
		Object [] maxRow = result.get(0);
		int max = 0;
		if(maxRow != null && maxRow.length > 0 && maxRow[0] != null){
			max = (Integer)maxRow[0];
			max ++;
		}
		return max;
	}
	
	public String getPrimaryKey(String table)throws Exception{
		ResultSet rs = null;
		Statement st = connection.createStatement();
		
		try {
			rs = connection.getMetaData().getPrimaryKeys(null, null, table);
			while(rs.next()){
				String col = rs.getString(4);
				String pri = rs.getString(6);
				//only single primary key 
				if("PRIMARY".equals(pri))
					return col;
			}
		} catch (Exception e) {
			throw e;
		} finally{
			closeResultSet(rs);
			closeStatement(st);
		}
		return null;
	}*/
	
}
